import json
import pytest
import inspect
# from config import *


def pytest_collection_modifyitems(items):
    global case_data
    if case_data["model"] == 1:
        case_data["cases_sort"].clear()
        for i, item in enumerate(items):
            case_data["cases_sort"].append({
                "sort": i,
                "name": item.name,
                "doc": inspect.getdoc(item.obj),
                "path": f"{item.parent.name} > {item.name}"
            })
    else:
        new_order = list()
        for case in case_data["execute_cases_list"]:
            for item in items:
                itm = str(item)[10:-1]
                if itm == case["funcname"]:
                    new_order.append(item)
                    items.remove(item)
                    break
        items[:] = new_order[:]


@pytest.mark.hookwrapper
def pytest_runtest_makereport(item, call):
    global recode_results_skip, recode_results_failed, recode_results_passed, outcome
    outcome = yield
    report = outcome.get_result()
    # res_coll[str(item)[10:-1]] = report.outcome
    report.description = str(item.function.__doc__)
    # if report.when == "call" and report.failed:
    #     判断失败进行截图
    #     allure.attach(chrome_driver.get_screenshot_as_png(), '失败截图', allure.attachment_type.PNG)
    report.nodeid = report.nodeid.encode("utf-8").decode("unicode_escape")
    if report.when == "setup":
        outcome = report.outcome
        result = {
            "name": str(report.nodeid).split("::")[1],
            "doc": report.description,
            "path": report.nodeid,
            "result": outcome,
            "err": report.longrepr
        }
        if outcome == "skipped":
            recode_results_skip.append(result)

    if report.when == "call" and outcome != "skipped":
        result = {
            "name": str(report.nodeid).split("::")[1],
            "doc": report.description,
            "path": report.nodeid,
            "result": outcome,
            "err": report.longrepr
        }
        if report.outcome == "failed":
            recode_results_failed.append(result)

        elif report.outcome == "passed":
            recode_results_passed.append(result)
